﻿#include "CalcCode.h"
#include <QFile>
#include <QDir>
#include <QVariantList>
#include <QDebug>
#include <QFileInfoList>
#include <QTextStream>
#include <QIODevice>

CalcCode::CalcCode(QObject *parent):QThread(parent)
{

}

CalcCode::~CalcCode()
{

}

void CalcCode::run()
{
    m_list.clear();

    readFiles();

    emit getValue(m_list);
}

void CalcCode::readFiles()
{
    QDir dir(m_path);

    calc(dir);
}

void CalcCode::setPath(const QString &path)
{
    m_path = path;
}
//迭代
void CalcCode::calc(const QDir &dir)
{
    QStringList filters;
    filters<<"*";

    QFileInfoList list = dir.entryInfoList(filters,QDir::NoDotAndDotDot | QDir::AllEntries,QDir::NoSort);


    for(int i=0;i<list.length();i++){

        QFileInfo fileInfo = list.at(i);

        if(fileInfo.isDir()){
            //目录
            QDir tempDir(fileInfo.filePath());
            calc(tempDir);
        }
        else{
            //文件
            calcLine(fileInfo.filePath());
        }
    }
}

void CalcCode::calcLine(const QString path)
{
    QFile file(path);

    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
        qDebug()<<"open error";
        return;
    }
    //
    int num = 0;

    QTextStream stream(&file);
    QString line;
    while (stream.readLineInto(&line)) {
        num++;
    }

    QStringList fileList = file.fileName().split(".");

    QVariantMap map;
    map.insert("filePath",file.fileName());
    map.insert("lineNum",num);
    map.insert("type",fileList.at(fileList.length()-1));

    getOneValue(map);   //item

    m_list.append(map);
    file.close();
}
